package DBside;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import Utils.Concurrent.TaskRunError;
import datatype.User;
import interfaces.UserManagement;

/**
 * @author Yuval
 * 
 *         implement the userManagment interface, this class create and execute
 *         all the queries for the user managment, create, update, get all users
 *         and so on.
 * 
 */

public class UserImplementation implements UserManagement {

	@Override
	public User getUserFromDB(String userName, String password, Statement stmt)
			throws TaskRunError {

		ResultSet rs;
		User user = null;
		try {
			rs = stmt.executeQuery("SELECT * FROM Users WHERE User_Name='"
					+ userName + "' AND Password='" + password + "'");
			if (!rs.next())
				return null;
			user = new User(rs.getString("First_Name"),
					rs.getString("Last_Name"), rs.getInt("Privilges"),
					rs.getString("Password"), rs.getString("User_Name"),
					rs.getInt("Id"), rs.getInt("Best_Long"),
					rs.getInt("Best_Level"), rs.getInt("Rank"));
			// closing
			rs.close();
			// / stmt.close();

		} catch (SQLException e) {
			System.out.println("ERROR executeQuery - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}
		return user;
	}

	@Override
	public int createUserInDB(String first_name, String last_name,
			String password, String user_name, Statement stmt)
			throws TaskRunError {

		int result;

		try {
			result = stmt.executeUpdate(
					"INSERT INTO Users(First_Name, Last_Name, Password, User_Name,Privilges)"
							+ " VALUES('" + first_name + "','" + last_name
							+ "','" + password + "','" + user_name + "',1)",
					new String[] { "Id" });
			ResultSet rs = stmt.getGeneratedKeys();
			rs.next();

			int id = rs.getInt(1);
			// closing

			// stmt.close();
			return id;
		} catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
			return 0;
		} catch (SQLException e) {
			System.out.println("ERROR executeUpdate - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection ");
		}
	}

	@Override
	public boolean createAdmin(Statement stmt) throws TaskRunError {

		try {
			stmt.executeUpdate("INSERT INTO Users(First_Name, Last_Name, Password, User_Name,Privilges)"
					+ " VALUES('Admin', 'Admin', 'Admin', 'Admin', 0)");

		} catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
		} catch (SQLException e) {
			System.out.println("ERROR executeUpdate - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection ");
		}
		return false;
	}

	@Override
	public boolean changePass(int userID, String newPassword, Statement stmt)
			throws TaskRunError {
		int result;

		try {
			result = stmt.executeUpdate("Update Users set Password ='"
					+ newPassword + "' where Id = " + userID);
			// closing
			stmt.close();

			return true;
		} catch (SQLException e) {
			System.out.println("ERROR executeUpdate - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}
	}

	@Override
	public List<User> getAllUsers(Statement stmt) throws TaskRunError {
		ResultSet rs;
		User user = null;
		try {
			rs = stmt.executeQuery("SELECT * FROM Users");

			List<User> users = new ArrayList<User>();
			while (rs.next()) {
				user = new User(rs.getString("First_Name"),
						rs.getString("Last_Name"), rs.getInt("Privilges"),
						rs.getString("Password"), rs.getString("User_Name"),
						rs.getInt("Id"), rs.getInt("Best_Long"),
						rs.getInt("Best_Level"), rs.getInt("Rank"));
				users.add(user);
			}
			// closing
			rs.close();
			// stmt.close();
			return users;
		} catch (SQLException e) {
			System.out.println("ERROR executeQuery - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}
	}

	@Override
	public boolean changeUsersPriv(List<Integer> toAdmin,
			List<Integer> toPlayer, Statement stm) throws TaskRunError {
		if (toAdmin != null)
			changePriv(0, toAdmin, stm);
		if (toPlayer != null)
			changePriv(1, toPlayer, stm);
		return false;
	}

	private void changePriv(int priv, List<Integer> usersId, Statement stmt)
			throws TaskRunError {

		try {

			for (int id : usersId) {
				String query = "Update Users set Privilges =" + priv
						+ " where Id = " + id;
				stmt.executeUpdate(query);
			}

		} catch (SQLException e) {
			System.out.println("ERROR executeUpdate - " + e.toString()); // java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}

	}

	@Override
	public boolean deleteUsers(List<Integer> users, Statement stm)
			throws TaskRunError {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isUsernameExist(String username, Statement stmt)
			throws TaskRunError {
		ResultSet rs;
		User user = null;
		try {
			rs = stmt.executeQuery("SELECT Id FROM Users WHERE User_Name='"
					+ username + "'");
			boolean res = rs.next();
			rs.close();
			// stmt.close();
			if (res)
				return true;
			else
				return false;

		} catch (SQLException e) {
			System.out.println("ERROR executeQuery - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}
	}

	@Override
	public boolean updateUserScore(int userID, int score, String mod,
			Statement stmt) throws TaskRunError {
		try {
			stmt.executeUpdate("Update Users set Best_" + mod + " = " + score
					+ "  where Id = " + userID);
			// closing
			// stmt.close();
		} catch (SQLException e) {
			System.out.println("ERROR executeUpdate - " + e.toString());
			// java.lang.System.exit(0);
			throw new TaskRunError("Connection Error");
		}
		return false;
	}

}
